import { EditOutlined, DeleteOutlined, ShareAltOutlined } from '@ant-design/icons';
import { page, del, batchDel, isActive, save, functionDetail, saveFunctionDetail, edit } from "@/views/sys/function/api";
import CloudTable from "@/component/CloudTable";
import TableDrawer from '@/component/TableDrawer';
import { useTable, useTableDialog } from "@/hooks/useTable";
import { Button, Space, Tooltip, Dropdown, DatePicker, Select, message } from 'antd';
import { STATUS_ENUMS, STATUS_OPTIONS } from './data';
import FormModal from '@/component/FormModal';
import { useFormDialog } from '@/hooks/useForm';
import dayjs from 'dayjs';
import { useEffect } from 'react';

const Function = () => {

    /**
     * 表单提交
     */
    const onFunctionFormCallback = (model) => {
        let data = {
            ...model,
            startDt: model.startDt?.format('YYYY-MM-DD'),
            endDt: model.endDt?.format('YYYY-MM-DD'),
        };
        functionFormModal.onSubmit(data, functionTable.onReload);
    }

    // 表单列
    const functionItems = [
        {
            label: '名称',
            name: 'name',
            rules: [{ required: true, message: '请输入名称' }],
        },
        {
            label: '生效时间',
            name: 'startDt',
            render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            rules: [{ required: true, message: '请选择生效时间' }],
        },
        {
            label: '失效时间',
            name: 'endDt',
            render: <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            rules: [{ required: true, message: '请选择失效时间' }],
        },
        {
            label: '状态',
            name: 'status',
            rules: [{ required: true, message: '请选择状态' }],
            render: <Select placeholder='请选择状态'
                options={[{
                    label: '启用',
                    value: 0,
                }, {
                    label: '停用',
                    value: 1,
                }]} />,
        },
        {
            label: '说明',
            name: 'description',
        },
    ]

    // 表单操作
    const functionFormModal = useFormDialog({
        width: 600,
        save: save,
        edit: edit,
        items: functionItems,
        callback: onFunctionFormCallback,
    });

    // 表格列
    const functionColumns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            fixed: 'left',
            align: 'center',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
            ellipsis: true,
            search: 'default'
        },
        {
            title: '生效时间',
            dataIndex: 'startDt',
            key: 'startDt',
            ellipsis: true,
            search: 'date'
        },
        {
            title: '失效时间',
            dataIndex: 'endDt',
            key: 'endDt',
            ellipsis: true,
            search: 'date',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            ellipsis: true,
            search: 'selected',
            options: STATUS_OPTIONS(),
            render: (val, row) => {
                let opts = [];
                if (val === 0) {
                    opts = [{
                        label: (
                            <a href='#' onClick={() => isActiveHandler(row.id, 1)}>
                                停用
                            </a>
                        ),
                        key: 0,
                    }]
                } else {
                    opts = [{
                        label: (
                            <a href='#' onClick={() => isActiveHandler(row.id, 0)}>
                                启用
                            </a>
                        ),
                        key: 1,
                    }]
                }
                return (
                    <Dropdown menu={{ items: opts }} trigger={['click']}>
                        <a onClick={e => e.preventDefault()}>
                            <Space>
                                {STATUS_ENUMS[val]}
                            </Space>
                        </a>
                    </Dropdown>
                )
            }
        },
        {
            title: '说明',
            dataIndex: 'description',
            key: 'description',
            width: 'auto',
            search: 'default',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 120,
            align: 'center',
            fixed: 'right',
            render: (val, row) => {
                let record = {
                    ...row,
                    startDt: row?.startDt ? dayjs(row.startDt, 'YYYY-MM-DD') : null,
                    endDt: row?.endDt ? dayjs(row.endDt, 'YYYY-MM-DD') : null,
                }
                return (
                    <div>
                        <Tooltip title="编辑">
                            <Button type="text" size="small" icon={<EditOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => functionFormModal.isOpenDialog(record, '编辑')} />
                        </Tooltip>
                        <Tooltip title="分配菜单">
                            <Button type="text" size="small" icon={<ShareAltOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => menuTableDrawer.isOpenDialog(record.id)} />
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => functionTable.onRemove(val)} />
                        </Tooltip>
                    </div>
                )
            }
        }
    ];

    // 表格工具栏
    const functionTools = () => {
        return (
            <Space>
                <Button type="primary" onClick={() => functionFormModal.isOpenDialog(undefined, '新增')} >新增</Button>
                <Button type='dashed' style={{ color: 'red' }} onClick={() => functionTable.onBatchRemove(functionTable.selected)}>删除</Button>
            </Space>
        );
    }

    // 表格操作
    const functionTable = useTable({
        reload: page,
        remove: del,
        batchRemove: batchDel,
        tools: functionTools,
        columns: functionColumns,
    });

    const onSaveFunctionDetailHandler = (model) => {
        saveFunctionDetail(model).then(resp => {
            if (resp?.data) {
                message.success('保存成功');
                menuTableDrawer.isOpenDialog();
            }
        });
    }

    // 菜单抽屉
    const menuTableDrawer = useTableDialog({
        title: '菜单',
        isPage: false,
        width: 250,
        reload: functionDetail,
        callback: onSaveFunctionDetailHandler,
        columns: [
            {
                title: '菜单名称',
                dataIndex: 'name',
                key: 'name',
                width: 'auto',
            },
        ],
    });

    // 功能包 停用/启用
    const isActiveHandler = (id, status) => {
        let model = {
            id: id,
            status: status,
        }
        isActive(model).then(resp => {
            if (resp?.data) {
                functionTable.onReload(undefined);
            }
        });
    }

    useEffect(() => {
        functionTable.onReload();
    }, []);

    return (
        <>
            <CloudTable props={functionTable} />
            <FormModal props={functionFormModal} />
            <TableDrawer props={menuTableDrawer} />
        </>
    )
}

export default Function;